package com.wuhao.shootclient.ui.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Build;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Animation;
import android.view.animation.Transformation;



import com.wuhao.shootclient.R;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * Create by hao on 2019-12-16
 */
public class FoldableMenu extends View {

    private boolean isOpen = false;
    private int rect = 0;
    private List<Integer> icon = new ArrayList();
    private MenuListener menuListener;

    private int realheight = 0;//真实高度

    private int bgColor;//背景颜色
    private boolean isVertical;//是否竖向
    private Bitmap clickBitMap;//点击icon图标


    public FoldableMenu(Context context) {
        this(context, null);
    }

    public FoldableMenu(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);

    }

    public FoldableMenu(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        if (!isClickable()) {
            setClickable(true);
        }

        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.FoldableMenu);

        bgColor = typedArray.getColor(R.styleable.FoldableMenu_bgColor, ContextCompat.getColor(context, R.color.bg_localmap));
        isVertical = typedArray.getBoolean(R.styleable.FoldableMenu_isVertical, true);
        clickBitMap = BitmapFactory.decodeResource(getContext().getResources(), typedArray.getResourceId(R.styleable.FoldableMenu_clickIcon, R.mipmap.ic_menu));


        typedArray.recycle();

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        boolean result = false;
        switch (event.getAction()) {
            case MotionEvent.ACTION_UP: {
                result = TouchMethod((int) event.getX(), (int) event.getY(), false);
                break;
            }
            case MotionEvent.ACTION_DOWN: {
                result = TouchMethod((int) event.getX(), (int) event.getY(), true);//
                break;
            }
        }
        if (result) {
            return true; //已消费事件
        } else {
            return false;//未消费事件
        }
    }

    private boolean TouchMethod(int x, int y, boolean isDown) {
        if (isVertical) {//竖向
            if (y > getMeasuredHeight() - getMeasuredWidth() && y < getMeasuredHeight()) {
                //如果点在底部按钮上
                if (!isDown) {
                    startAnimation();
                }
                return true;
            } else if (y > 0 && y < getMeasuredHeight() - getMeasuredWidth() && isOpen) {
                //如果点在选项上，并且按钮在展开状态
                if (!isDown) {
                    for (int i = icon.size(); i > 0; i--) {
                        //计算并判断点在了哪个位置（view的宽度为Width，高度为icon.size*Width,相当于每个图标所占的区域都是正方形）
                        if (y > (i - 1) * getMeasuredWidth() && y < i * getMeasuredWidth()) {
                            if (menuListener != null) {
                                menuListener.onClick(icon.size() - i + 1);//调用接口
                            }
                        }
                    }
                }
                return true;
            } else {
                return false;//按钮未展开
            }
        } else {
            if (x > 0 && x < getMeasuredHeight()) {
                //如果点在左部按钮上
                if (!isDown) {
                    startAnimation();
                }
                return true;
            } else if (x > getMeasuredHeight() && x < getMeasuredWidth() && isOpen) {
                //如果点在选项上，并且按钮在展开状态
                if (!isDown) {
                    if (isVertical) {
                        for (int i = icon.size(); i > 0; i--) {
                            //计算并判断点在了哪个位置（view的宽度为Width，高度为icon.size*Width,相当于每个图标所占的区域都是正方形）
                            if (y > (i - 1) * getMeasuredWidth() && y < i * getMeasuredWidth()) {
                                if (menuListener != null) {
                                    menuListener.onClick(icon.size() - i + 1);//调用接口
                                }
                            }
                        }
                    } else {
                        for (int i = icon.size(); i > 0; i--) {
                            //计算并判断点在了哪个位置（view的宽度为Width，高度为icon.size*Width,相当于每个图标所占的区域都是正方形）
                            if (x > i * getMeasuredHeight() && x < (i + 1) * getMeasuredHeight()) {
                                if (menuListener != null) {
                                    menuListener.onClick(i);//调用接口
                                }
                            }
                        }
                    }

                }
                return true;
            } else {
                return false;//按钮未展开
            }
        }

    }

    Paint mPaint = new Paint();
    Path path = new Path();


    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onDraw(Canvas canvas) {
        // super.onDraw(canvas);
        if (isVertical) {
            int px = getMeasuredWidth() / 2;

            mPaint.setColor(bgColor);       //设置画笔颜色
            mPaint.setStyle(Paint.Style.FILL);  //设置画笔模式为填充
            mPaint.setStrokeWidth(10f);//设置画笔宽度为10px
            mPaint.setAntiAlias(true);

            path.setFillType(Path.FillType.EVEN_ODD);
            canvas.translate(px, getMeasuredHeight() - px);//移动坐标中心

            canvas.drawArc(-px, -px, px, px, 0, 180, true, mPaint);//画出底部的半圆
            canvas.drawArc(-px, -px - rect, px, -rect + px, 180, 180, true, mPaint); //画出上部分的半圆
            canvas.drawRect(-px, -rect, px, 0, mPaint);//画出两个半圆中间的矩形

            canvas.drawBitmap(clickBitMap, -clickBitMap.getWidth() / 2, -clickBitMap.getHeight() / 2, mPaint); //获取并绘制按钮没有展开时的图标

            for (int i = 0; i < icon.size(); i++) {
                if (rect >= 2 * px * (i + 1)) {
                    //2*px=getMeasuredWidth(),i+1=当前的图标个数(-y)，如果上升高度足够显示下一个图标，就绘制
                    Bitmap bitmap1 = BitmapFactory.decodeResource(getContext().getResources(), icon.get(i).intValue());
                    canvas.drawBitmap(bitmap1, -clickBitMap.getWidth() / 2, -clickBitMap.getHeight() / 2 - (i + 1) * 2 * px, mPaint);//在相应位置绘制图标
                }
            }

            if (rect == realheight) {//完全展开
                isOpen = true;

            } else if (rect == 0) {    //完全闭合
                isOpen = false;
            }
        } else {
            int px = getMeasuredHeight() / 2;

            mPaint.setColor(bgColor);       //设置画笔颜色
            mPaint.setStyle(Paint.Style.FILL);  //设置画笔模式为填充
            mPaint.setStrokeWidth(10f);//设置画笔宽度为10px
            mPaint.setAntiAlias(true);

            path.setFillType(Path.FillType.EVEN_ODD);
            canvas.translate(px, px);//移动坐标中心


            canvas.drawArc(-px, -px, px, px, 90, 180, true, mPaint);//画出左部的半圆
            canvas.drawArc(-px + rect, -px, px + rect, px, -90, 180, true, mPaint); //画出右部的半圆

            canvas.drawRect(0, -px, rect, px, mPaint);//画出两个半圆中间的矩形

            canvas.drawBitmap(clickBitMap, -clickBitMap.getWidth() / 2, -clickBitMap.getHeight() / 2, mPaint); //获取并绘制按钮没有展开时的图标

            for (int i = 0; i < icon.size(); i++) {
                if (rect >= 2 * px * (i + 1)) {
                    //2*px=getMeasuredWidth(),i+1=当前的图标个数(-y)，如果上升高度足够显示下一个图标，就绘制
                    Bitmap bitmap1 = BitmapFactory.decodeResource(getContext().getResources(), icon.get(i).intValue());
                    canvas.drawBitmap(bitmap1, -clickBitMap.getWidth() / 2 + (i + 1) * 2 * px, -clickBitMap.getHeight() / 2, mPaint);//在相应位置绘制图标
                }
            }

            if (rect == realheight) {//完全展开
                isOpen = true;

            } else if (rect == 0) {    //完全闭合
                isOpen = false;
            }
        }
        if (menuListener != null) {
            menuListener.onOpen(isOpen);
        }

    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int width;
        int height;

        width = MeasureSpec.getSize(widthMeasureSpec);
        height = MeasureSpec.getSize(heightMeasureSpec);

        //取较小的
        width = width > height ? height : width;
        height = height > width ? width : height;

        if (isVertical) {
            height += icon.size() * width;//根据加入图标个数累加view高度
            realheight = height - width;//加入图标的总高度
        } else {
            width += icon.size() * width;
            realheight = width - height;//加入图标的总高度
        }

        setMeasuredDimension(width, height);
    }

    public void setMenuListener(MenuListener menuListener) {
        this.menuListener = menuListener;
    }

    //展开菜单动画
    private class AnimOpen extends Animation {

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            rect = (int) (interpolatedTime * (realheight));
            invalidate();
        }

    }

    //关闭菜单动画
    private class AnimClose extends Animation {

        @Override
        protected void applyTransformation(float interpolatedTime, Transformation t) {
            super.applyTransformation(interpolatedTime, t);
            rect = (int) ((1 - interpolatedTime) * (realheight));
            invalidate();
        }

    }

    private void startAnimation() {
        if (!isOpen) {
            AnimOpen move = new AnimOpen();
            move.setDuration(300);
            move.setInterpolator(new AccelerateDecelerateInterpolator());
            startAnimation(move);
        } else {
            AnimClose move = new AnimClose();
            move.setDuration(300);
            move.setInterpolator(new AccelerateDecelerateInterpolator());
            startAnimation(move);
        }
    }


    //***************************** 对外提供 操作方法  ******************************

    /**
     * 需实现此接口以便接受点击事件
     */
    public interface MenuListener {
        void onClick(int index);

        void onOpen(boolean isClose);
    }


    /**
     * 不加动画 直接缩回去
     */
    public void closeMenuNoAnim() {
        rect = 0;
        invalidate();
    }

    /**
     * 设置菜单icon
     */
    public void setIconResId(@DrawableRes Integer... id) {
        this.icon = Arrays.asList(id);
    }

    /**
     * 设置菜单icon list
     */
    public void setIconList(List<Integer> iconList) {
        this.icon.addAll(iconList);
    }

    /**
     * 设置背景颜色
     *
     * @param bgColor
     */
    public void setBgColor(int bgColor) {
        this.bgColor = bgColor;
    }

    /**
     * 设置是否竖向
     *
     * @param vertical
     */
    public void setVertical(boolean vertical) {
        isVertical = vertical;
    }

    /**
     * 获取当前menu是否展开状态
     *
     * @return
     */
    public boolean isOpen() {
        return isOpen;
    }
}